package com.security.it.web.async;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;

@Slf4j
@RestController
@RequestMapping(value = "order", produces = "application/json")
public class AsyncController {

    @Autowired
    private MockQueue mockQueue;
    @Autowired
    private DeferredResultHolder deferredResultHolder;

    @GetMapping("/submit")
    public Callable<String> order() {
        log.info("main thread start");
        Callable<String> result = () -> {
            log.info("副线程开始");
            Thread.sleep(3000);
            log.info("副线程结束");
            return "success";
        };
        log.info("main thread end");
        return result;
    }

    @GetMapping("/submitNew")
    public DeferredResult<String> orderNew() throws InterruptedException {
        log.info("main thread start");
        String orderNumber = RandomStringUtils.randomNumeric(8);
        mockQueue.setPlaceOrder(orderNumber);

        DeferredResult<String> deferredResult = new DeferredResult<>();
        deferredResultHolder.getMap().put(orderNumber, deferredResult);
        log.info("main thread end");
        return deferredResult;
    }
}
